package calculator;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.imageio.ImageIO;

public class Calculator extends JFrame implements ActionListener {
    private JPanel north, center;
    private JTextField field;
    private JButton[] btns;
    private boolean isTimeShowing = false;
    private String previousContent = "";

    // 主题相关变量
    private boolean isDarkMode = false;
    private Color bgColorLight = Color.WHITE;
    private Color bgColorDark = new Color(30, 30, 30);
    private Color textColorLight = Color.BLACK;
    private Color textColorDark = Color.WHITE;
    private Color btnColorLight = new Color(220, 220, 220);
    private Color btnColorDark = new Color(60, 60, 60);
    private Color btnOpColorLight = new Color(255, 165, 0);
    private Color btnOpColorDark = new Color(255, 140, 0);

    // 背景图片变量
    private BufferedImage backgroundImage;
    private BackgroundPanel backgroundPanel; 

    public Calculator() {
        setTitle("计算器");
        setSize(700, 700);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 加载背景图片（替换为你的图片路径）
        loadBackgroundImage(); 

        initComponent();
        setVisible(true);
    }

    // 加载背景图片方法
    private void loadBackgroundImage() {
        try {
            // 示例：从项目资源目录加载，也可写绝对路径如 "C:/images/bg.jpg"
            backgroundImage = ImageIO.read(getClass().getResource("/background.jpg")); 
        } catch (IOException e) {
            System.err.println("背景图片加载失败: " + e.getMessage());
            backgroundImage = null; // 加载失败时用纯色背景
        }
    }

    private void initComponent() {
        // 初始化带背景的内容面板
        backgroundPanel = new BackgroundPanel();
        setContentPane(backgroundPanel);
        backgroundPanel.setLayout(new BorderLayout()); 

        north = new JPanel();
        center = new JPanel();
        field = new JTextField();
        field.setPreferredSize(new Dimension(700, 150));
        field.setEditable(false);
        field.setOpaque(false);
        //field.setForeground(Color.PINK);
        field.setFont(new Font("SansSerif", Font.BOLD, 35));

        String[] str = new String[] {
            "7", "8", "9", "+",
            "4", "5", "6", "-",
            "1", "2", "3", "×",
            "0", ".", "=", "÷",
            "C", "B", "T", "S"
        };

        btns = new JButton[str.length];
        for (int i = 0; i < btns.length; i++) {
            btns[i] = new JButton(str[i]);
            btns[i].setFont(new Font("SansSerif", Font.BOLD, 35));
            // 重新设置按钮大小（示例：宽120，高80）
            btns[i].setPreferredSize(new Dimension(120, 80)); 
        }

        north.setLayout(new BorderLayout());
        center.setLayout(new GridLayout(5, 4, 10, 10)); // 增加网格间距，让按钮更美观

        // 让面板透明，避免遮挡背景
        north.setOpaque(false);
        center.setOpaque(false);

        north.add(field, BorderLayout.CENTER);

        for (JButton btn : btns) {
            center.add(btn);
        }

        backgroundPanel.add(north, BorderLayout.NORTH);
        backgroundPanel.add(center, BorderLayout.CENTER);

        for (JButton btn : btns) {
            btn.addActionListener(this);
        }

        // 应用初始主题
        applyTheme();
    }

    private void setBtnText(String text) {
        // ... 原有逻辑不变 ...
        switch (text) {
            case "C":
                field.setText("");
                isTimeShowing = false;
                previousContent = "";
                break;
            case "B":
                if (isTimeShowing) {
                    return;
                }
                String numText = field.getText();
                if (numText.length() != 0) {
                    String lastText = numText.substring(0, numText.length() - 1);
                    field.setText(lastText);
                }
                break;
            case "T":
                showCurrentTime();
                break;
            case "S":
                toggleTheme();
                break;
            case "=":
                if (isTimeShowing) {
                    return;
                }
                calculate();
                break;
            default:
                if (isTimeShowing) {
                    isTimeShowing = false;
                    field.setText("");
                }

                String oldText = field.getText();

                if (text.equals(".")) {
                    if (oldText.isEmpty()) {
                        field.setText("0.");
                        return;
                    }

                    char lastChar = oldText.charAt(oldText.length() - 1);
                    if (lastChar == '.') {
                        return;
                    }

                    if (isOperator(String.valueOf(lastChar))) {
                        field.setText(oldText + "0" + text);
                        return;
                    }

                    String currentNumber = getCurrentNumber(oldText);
                    if (currentNumber.contains(".")) {
                        return;
                    }
                } else if (isOperator(text)) {
                    if (oldText.isEmpty() || isOperator(String.valueOf(oldText.charAt(oldText.length() - 1))) || oldText.charAt(oldText.length() - 1) == '.') {
                        return;
                    }
                }

                field.setText(oldText + text);
                break;
        }
    }

    private boolean isOperator(String text) {
        return text.equals("+") || text.equals("-") || text.equals("×") || text.equals("÷");
    }

    private String getCurrentNumber(String expression) {
        for (int i = expression.length() - 1; i >= 0; i--) {
            char c = expression.charAt(i);
            if (isOperator(String.valueOf(c))) {
                return expression.substring(i + 1);
            }
        }
        return expression;
    }

    private void showCurrentTime() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);

        if (!isTimeShowing) {
            previousContent = field.getText();
            isTimeShowing = true;
        }

        field.setText(formattedDateTime);
    }

    private void calculate() {
        String expression = field.getText();
        expression = expression.replace("×", "*").replace("÷", "/");

        if (!expression.isEmpty() && isOperator(String.valueOf(expression.charAt(expression.length() - 1)))) {
            expression = expression.substring(0, expression.length() - 1);
        }

        if (expression.isEmpty()) {
            return;
        }

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        try {
            Object result = engine.eval(expression);
            field.setText(result.toString());
            isTimeShowing = false;
            previousContent = "";
        } catch (ScriptException e) {
            field.setText("运算错误");
            e.printStackTrace();
            isTimeShowing = false;
            previousContent = "";
        }
    }

    // 切换主题
    private void toggleTheme() {
        isDarkMode = !isDarkMode;
        applyTheme();

        // 显示主题切换提示
        field.setText(isDarkMode ? "暗色模式已启用" : "亮色模式已启用");
    }

    // 应用主题
    private void applyTheme() {
        // 设置背景（如果图片加载失败，用纯色兜底）
        if (backgroundImage == null) {
            backgroundPanel.setSolidColor(isDarkMode ? bgColorDark : bgColorLight);
        }

        // 设置文本框样式
        field.setBackground(isDarkMode ? bgColorDark : bgColorLight);
        field.setForeground(isDarkMode ? textColorDark : textColorLight);

        // 设置按钮样式
        for (JButton btn : btns) {
            // 操作符按钮使用特殊颜色
            if (isOperator(btn.getText()) || btn.getText().equals("=")) {
                btn.setBackground(isDarkMode ? btnOpColorDark : btnOpColorLight);
            } else {
                btn.setBackground(isDarkMode ? btnColorDark : btnColorLight);
            }
            btn.setForeground(isDarkMode ? textColorDark : textColorLight);

            // 移除按钮边框（可选，若需要边框可改为 true）
            btn.setBorderPainted(false);
            btn.setFocusPainted(false);
        }

        // 刷新界面
        revalidate();
        repaint();
    }

    @Override
    public void actionPerformed(ActionEvent a) {
        Object source = a.getSource();
        if (source instanceof JButton) {
            JButton btn = (JButton) source;
            String text = btn.getText();
            setBtnText(text);
        }
    }

    // 自定义背景面板（支持图片或纯色）
    private class BackgroundPanel extends JPanel {
        private Color solidColor = Color.WHITE; // 图片加载失败时用纯色

        public BackgroundPanel() {
            setOpaque(false);
        }

        // 暴露方法设置纯色（主题切换时用）
        public void setSolidColor(Color color) {
            this.solidColor = color;
            repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (backgroundImage != null) {
                // 绘制背景图片，自适应窗口大小
                g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
            } else {
                // 图片加载失败，绘制纯色
                g.setColor(solidColor);
                g.fillRect(0, 0, getWidth(), getHeight());
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(Calculator::new);
    }
}